if(window.io == null){
    window.io = require("socket-io");
}
 
var Net = cc.Class({
    extends: cc.Component,
    statics: {
        ip:"",
        uid:"",
        scene:"",
        alert:"",
        loading:"",
        sio:null,
        isPinging:false,
        fnDisconnect:null,
        handlers:{},
        addHandler:function(event,fn){
            if(this.handlers[event]){
                console.log("event:" + event + "' handler has been registered.");
                return;
            }

            var handler = function(data){
                // if(event != "disconnect" && typeof(data) == "string"){
                //     data = JSON.parse(data);
                // }
                fn(data);
            };
            
            this.handlers[event] = handler; 
            if(this.sio){
                console.log("register:function " + event);
                this.sio.on(event,handler);
            }
        },
        removeAllHandlers:function(){
            this.handlers = {};
        },
        connect:function(fnConnect,fnError) {
            var self = this;
            
            var opts = {
                'reconnection':false,
                'force new connection': true,
                'transports':['websocket', 'polling']
            }
            cc.log("connect server:", this.ip+"?uid="+this.uid+"&scene="+this.scene);
            this.sio = window.io.connect(this.ip+"?uid="+this.uid+"&scene="+this.scene, opts);
            this.sio.on('reconnect',function(){
                console.log('reconnection');
            });
            this.sio.on('connect',function(data){
                console.log("connect");
                self.sio.connected = true;
                fnConnect(data);
            });
            
            this.sio.on('disconnect',function(data){
                console.log("disconnect");
                self.sio.connected = false;
                self.close();
            });
            
            this.sio.on('connect_failed',function (){
                console.log('connect_failed');
            });
            
            for(var key in this.handlers){
                var value = this.handlers[key];
                if(typeof(value) == "function"){
                    if(key == 'disconnect'){
                        this.fnDisconnect = value;
                    }
                    else{
                        console.log("register:function " + key);
                        this.sio.on(key,value);                        
                    }
                }
            }
            
            //this.startHearbeat();
        },

        send:function(event, data, callback){
            console.log("sendEvent:", event);
            var self = this;
            if(this.sio && this.sio.connected){
                // show loading
                this.loading.show();
                // if(data != null && (typeof(data) == "object")){
                //     data = JSON.stringify(data);
                //     //console.log(data);              
                // }
                this.sio.emit(event, data, function(backData1, backData2){
                    // cc.log(backData1, backData2);
                    self.loading.hide();
                    callback(backData1, backData2);
                });
            }else{
                // alert not connect
                this.alert.show("与服务器断开连接");
            }
        },
        
        startHearbeat:function(){
            this.sio.on('game_pong',function(){
                console.log('game_pong');
                self.lastRecieveTime = Date.now();
                self.delayMS = self.lastRecieveTime - self.lastSendTime;
                console.log(self.delayMS);
            });
            this.lastRecieveTime = Date.now();
            var self = this;
            console.log(1);
            if(!self.isPinging){
                self.isPinging = true;
                cc.game.on(cc.game.EVENT_HIDE,function(){
                    self.ping();
                });
                setInterval(function(){
                    if(self.sio){
                        self.ping();                
                    }
                }.bind(this),5000);
                setInterval(function(){
                    if(self.sio){
                        if(Date.now() - self.lastRecieveTime > 10000){
                            self.close();
                        }         
                    }
                }.bind(this),500);
            }   
        },
        
        ping:function(){
            if(this.sio){
                this.lastSendTime = Date.now();
                this.send('game_ping');
            }
        },
        
        close:function(){
            console.log('close');
            this.delayMS = null;
            if(this.sio && this.sio.connected){
                this.sio.connected = false;
                this.sio.disconnect();
            }
            this.sio = null;
            if(this.fnDisconnect){
                this.fnDisconnect();
                this.fnDisconnect = null;
            }
            this.removeAllHandlers();
        },
        
        // test:function(fnResult){
        //     var xhr = null;
        //     var fn = function(ret){
        //         fnResult(ret.isonline);
        //         xhr = null;
        //     }
            
        //     var arr = this.ip.split(':');
        //     var data = {
        //         //account:cc.vv.userMgr.account,
        //         //sign:cc.vv.userMgr.sign,
        //         ip:arr[0],
        //         port:arr[1],
        //     }
        //     xhr = HTTP.sendRequest("/is_server_online",data,fn);
        //     setTimeout(function(){
        //         if(xhr){
        //             xhr.abort();
        //             fnResult(false);                    
        //         }
        //     },1500);
        //     /*
        //     var opts = {
        //         'reconnection':false,
        //         'force new connection': true,
        //         'transports':['websocket', 'polling']
        //     }
        //     var self = this;
        //     this.testsio = window.io.connect(this.ip,opts);
        //     this.testsio.on('connect',function(){
        //         console.log('connect');
        //         self.testsio.close();
        //         self.testsio = null;
        //         fnResult(true);
        //     });
        //     this.testsio.on('connect_error',function(){
        //         console.log('connect_failed');
        //         self.testsio = null;
        //         fnResult(false);
        //     });
        //     */
        // }
    },
});